package server.util;

/**
 *
 * @author Michael Hanns
 *
 */
public class FixTelnetInput {

    public static String fix(String input) {
        if(input == null || input.length() == 0) {
            return "";
        }
        char[] inpChars = input.toCharArray();
        
        int bkSpcFirstOccurence = 0;
        int totalBkSpcs = 0;
        for (int c = 0; c < inpChars.length; c++) {
            if(inpChars[c] == 8) {
                if(bkSpcFirstOccurence > 0) {
                    totalBkSpcs++;
                } else {
                    bkSpcFirstOccurence = c;
                }
            } else {
                if(bkSpcFirstOccurence > 0) {
                    int count = 0;
                    while(bkSpcFirstOccurence > 0 && count < totalBkSpcs) {
                        inpChars[--bkSpcFirstOccurence] = 8;
                        count++;
                    }
                }
            }
        }
        input = String.valueOf(inpChars).replace(((char)8)+"", "");
        return input;
    }
}
